<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="welcome" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Java并发工具类(JUC) |  ChenyyのBlog
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">
  
<link rel="stylesheet" href="/css/custom.css">

  
  <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-Java/Java并发工具类(JUC)"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Java并发工具类(JUC)
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2021/06/08/Java/Java%E5%B9%B6%E5%8F%91%E5%B7%A5%E5%85%B7%E7%B1%BB(JUC)/" class="article-date">
  <time datetime="2021-06-08T12:21:58.000Z" itemprop="datePublished">2021-06-08</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java/">Java</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">3.9k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">16 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <ul>
<li>等待多线程完成CountDownLatch</li>
<li>同步屏障CyclicBarrier</li>
<li>控制并发线程数Semaphore</li>
<li>线程间交换数据Exchanger</li>
</ul>
<span id="more"></span>

<p>在J.U.C包中，提供了几个非常有用的并发工具类，CountDownLatch、CyclicBarrier和Semaphore工具类提供了一种并发流程控制的手段，Exchanger工具类则提供了在线程间交换数据的一种手段。</p>
<p>通过使用这些工具类，可以有效提高并发编程中，并发流程的控制，以提升效率和代码质量。</p>
<h1 id="等待多线程完成的CountDownLatch"><a href="#等待多线程完成的CountDownLatch" class="headerlink" title="等待多线程完成的CountDownLatch"></a>等待多线程完成的CountDownLatch</h1><p>CountDownLatch允许一个或多个线程等待其他线程完成操作。</p>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><p>CountDownLatch的构造函数接收一个int类型的参数作为计数器，如果你想等待N个点完成，这里就传入N。可以是N个线程，也可以是1个线程里的N个执行步骤。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CountDownLatch countDown=new CountDownLatch(N);</span><br></pre></td></tr></table></figure>

<p>当我们调用CountDownLatch的<code>countDown</code>方法时，N就会减1，CountDownLatch的<code>await</code>方法会阻塞当前线程，直到N变成零。</p>
<p>如果有某个线程处理得比较慢，可以使用另外一个带指定时间的await方法——<code>await（long time，TimeUnit unit）</code>，这个方法等待特定时间后，就会不再阻塞当前线程。join也有类似的方法。</p>
<p>注意：计数器必须大于等于0，等于0时相当于不会阻塞当前线程。<strong>同时CountDownLatch不能重新初始化或者修改CountDownLatch对象的内部计数器。</strong>一个线程调用countDown方法happen-before，另外一个线程调用await方法。</p>
<h2 id="跟join-方法对比"><a href="#跟join-方法对比" class="headerlink" title="跟join()方法对比"></a>跟join()方法对比</h2><p>在代码实现中，我们也可以使用join()方法，让当前执行线程等待join线程执行结束。join的实现原理是不断的去判断join的线程是否存活，如果存活，则让当前线程一直等待。</p>
<h2 id="测试类"><a href="#测试类" class="headerlink" title="测试类"></a>测试类</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">import java.util.Random;</span><br><span class="line">import java.util.concurrent.CountDownLatch;</span><br><span class="line">import java.util.concurrent.atomic.AtomicInteger;</span><br><span class="line"> </span><br><span class="line">public class CountDownLatchTest &#123;</span><br><span class="line">	private static Random sr=new Random(47); </span><br><span class="line">	private static AtomicInteger result=new AtomicInteger(0);</span><br><span class="line">	private static int threadCount=10;//线程数量</span><br><span class="line">	private static CountDownLatch countDown=new CountDownLatch(threadCount);//CountDownLatch</span><br><span class="line">	private static class Parser implements Runnable&#123; </span><br><span class="line">		String name;</span><br><span class="line">		public Parser(String name)&#123;</span><br><span class="line">			this.name=name;</span><br><span class="line">		&#125;</span><br><span class="line">		@Override</span><br><span class="line">		public void run() &#123;</span><br><span class="line">			int sum=0;</span><br><span class="line">			int seed=Math.abs(sr.nextInt()) ;</span><br><span class="line">			Random r=new Random(47); </span><br><span class="line">			for(int i=0;i&lt;100;i++)&#123;  </span><br><span class="line">				sum+=r.nextInt(seed);</span><br><span class="line">			&#125;  </span><br><span class="line">			result.addAndGet(sum);</span><br><span class="line">			System.out.println(name+&quot;线程的解析结果：&quot;+sum);</span><br><span class="line">			countDown.countDown();//注意这里</span><br><span class="line">		&#125; </span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args) throws InterruptedException &#123;</span><br><span class="line">		Thread[] threads=new Thread[threadCount];</span><br><span class="line">		for(int i=0;i&lt;threadCount;i++)&#123;</span><br><span class="line">			threads[i]=new Thread(new Parser(&quot;Parser-&quot;+i));</span><br><span class="line">		&#125; </span><br><span class="line">		for(int i=0;i&lt;threadCount;i++)&#123;</span><br><span class="line">			threads[i].start();</span><br><span class="line">		&#125; </span><br><span class="line">		/*</span><br><span class="line">		for(int i=0;i&lt;threadCount;i++)&#123;</span><br><span class="line">			threads[i].join();</span><br><span class="line">		&#125;*/</span><br><span class="line">		countDown.await();//将join改为使用CountDownLatch</span><br><span class="line">		System.out.println(&quot;所有线程解析结束！&quot;);</span><br><span class="line">		System.out.println(&quot;所有线程的解析结果：&quot;+result);</span><br><span class="line">	&#125; </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">输出：</span><br><span class="line">Parser-0线程的解析结果：1336321192</span><br><span class="line">Parser-1线程的解析结果：-2013585201</span><br><span class="line">Parser-2线程的解析结果：-1675827227</span><br><span class="line">Parser-4线程的解析结果：1638121055</span><br><span class="line">Parser-3线程的解析结果：908136818</span><br><span class="line">Parser-5线程的解析结果：1513365118</span><br><span class="line">Parser-7线程的解析结果：489607354</span><br><span class="line">Parser-6线程的解析结果：1513365118</span><br><span class="line">Parser-8线程的解析结果：-1191966831</span><br><span class="line">Parser-9线程的解析结果：-912399159</span><br><span class="line">所有线程解析结束！</span><br><span class="line">所有线程的解析结果：1605138237</span><br></pre></td></tr></table></figure>



<h2 id="源码"><a href="#源码" class="headerlink" title="源码"></a>源码</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">public class CountDownLatch &#123;</span><br><span class="line">    /**Synchronization control For CountDownLatch. Uses AQS state to represent count.*/</span><br><span class="line">    private static final class Sync extends AbstractQueuedSynchronizer &#123;</span><br><span class="line">        private static final long serialVersionUID = 4982264981922014374L;</span><br><span class="line"> </span><br><span class="line">        Sync(int count) &#123;</span><br><span class="line">            setState(count);//初始化同步状态</span><br><span class="line">        &#125;</span><br><span class="line"> </span><br><span class="line">        int getCount() &#123;</span><br><span class="line">            return getState();</span><br><span class="line">        &#125;</span><br><span class="line"> </span><br><span class="line">        protected int tryAcquireShared(int acquires) &#123;</span><br><span class="line">            return (getState() == 0) ? 1 : -1;</span><br><span class="line">        &#125;</span><br><span class="line"> </span><br><span class="line">        protected boolean tryReleaseShared(int releases) &#123;</span><br><span class="line">            // Decrement count; signal when transition to zero</span><br><span class="line">            for (;;) &#123;</span><br><span class="line">                int c = getState();</span><br><span class="line">                if (c == 0)</span><br><span class="line">                    return false;</span><br><span class="line">                int nextc = c-1;</span><br><span class="line">                if (compareAndSetState(c, nextc))</span><br><span class="line">                    return nextc == 0;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    private final Sync sync;//组合一个同步器（AQS）</span><br><span class="line"> </span><br><span class="line">    public CountDownLatch(int count) &#123;</span><br><span class="line">        if (count &lt; 0) throw new IllegalArgumentException(&quot;count &lt; 0&quot;);</span><br><span class="line">        this.sync = new Sync(count);//初始化同步状态</span><br><span class="line">    &#125;</span><br><span class="line">    /*Causes the current thread to wait until the latch has counted down to</span><br><span class="line">     * zero, unless the thread is &#123;@linkplain Thread#interrupt interrupted&#125;.*/</span><br><span class="line">    public void await() throws InterruptedException &#123;</span><br><span class="line">        sync.acquireSharedInterruptibly(1);//</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    public boolean await(long timeout, TimeUnit unit)</span><br><span class="line">        throws InterruptedException &#123;</span><br><span class="line">        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));</span><br><span class="line">    &#125;</span><br><span class="line">    public void countDown() &#123;</span><br><span class="line">        sync.releaseShared(1);//释放同步状态</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    public long getCount() &#123;</span><br><span class="line">        return sync.getCount();</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    public String toString() &#123;</span><br><span class="line">        return super.toString() + &quot;[Count = &quot; + sync.getCount() + &quot;]&quot;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h1 id="同步屏障CyclicBarrier"><a href="#同步屏障CyclicBarrier" class="headerlink" title="同步屏障CyclicBarrier"></a>同步屏障CyclicBarrier</h1><h2 id="使用-1"><a href="#使用-1" class="headerlink" title="使用"></a>使用</h2><p>CyclicBarrier意思是可循环使用（Cyclic）的屏障（Barrier）。可以让一组线程到达一个屏障（也可以叫同步点）时被阻塞，直到最后一个线程到达屏障时，屏障才会开门，所有被屏障拦截的线程才会继续运行。</p>
<p>CyclicBarrier默认的构造方法是<code>CyclicBarrier（int parties）</code>，其参数表示屏障拦截的线程数量，每个线程通过调用CyclicBarrier的<code>await()</code>方法，通知CyclicBarrier当前线程已经到达屏障，然后当前线程被阻塞。</p>
<h2 id="CyclicBarrier与CountDownLatch的区别"><a href="#CyclicBarrier与CountDownLatch的区别" class="headerlink" title="CyclicBarrier与CountDownLatch的区别"></a>CyclicBarrier与CountDownLatch的区别</h2><p>CyclicBarrier的计数器可以使用reset()进行重置，而CountDownLatch的计数器不可重置只能使用一次。如果计算发生错误，可以重置计数器，并让线程重新执行一次。</p>
<p>CyclicBarrier提供了比CountDownLatch更丰富的方法。<code>isBroken()</code>用于了解阻塞的线程是否被中断。<code>getNumberWaiting()</code>方法可以获取被CyclicBarrier阻塞的线程数。</p>
<h2 id="测试类-1"><a href="#测试类-1" class="headerlink" title="测试类"></a>测试类</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line">import java.util.Random; </span><br><span class="line">import java.util.concurrent.CyclicBarrier;</span><br><span class="line">import java.util.concurrent.atomic.AtomicInteger;</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">public class CyclicBarrierTest &#123;</span><br><span class="line"> </span><br><span class="line">	private static Random sr=new Random(47); </span><br><span class="line">	private static AtomicInteger result=new AtomicInteger(0);</span><br><span class="line">	private static int threadCount=10;</span><br><span class="line">	//屏障后面执行汇总</span><br><span class="line">	private static CyclicBarrier barrier=new CyclicBarrier(threadCount,new Accumulate());</span><br><span class="line">	private static class Parser implements Runnable&#123; </span><br><span class="line">		String name;</span><br><span class="line">		public Parser(String name)&#123;</span><br><span class="line">			this.name=name;</span><br><span class="line">		&#125;</span><br><span class="line">		@Override</span><br><span class="line">		public void run() &#123;</span><br><span class="line">			int sum=0;</span><br><span class="line">			int seed=Math.abs(sr.nextInt()) ;</span><br><span class="line">			Random r=new Random(47); </span><br><span class="line">			for(int i=0;i&lt;(seed%100*100000);i++)&#123;  </span><br><span class="line">				sum+=r.nextInt(seed); </span><br><span class="line">			&#125;  </span><br><span class="line">			result.addAndGet(sum);</span><br><span class="line">			System.out.println(System.currentTimeMillis()+&quot;-&quot;+name+&quot;线程的解析结果：&quot;+sum);</span><br><span class="line">			try &#123; </span><br><span class="line">				barrier.await();</span><br><span class="line">				System.out.println(System.currentTimeMillis()+&quot;-&quot;+name+&quot;线程越过屏障！&quot;);</span><br><span class="line">			&#125; catch (Exception e) &#123;</span><br><span class="line">				e.printStackTrace();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125; </span><br><span class="line">	&#125;</span><br><span class="line">	static class Accumulate implements Runnable&#123; </span><br><span class="line">		@Override</span><br><span class="line">		public void run() &#123; </span><br><span class="line">			System.out.println(&quot;所有线程解析结束！&quot;);</span><br><span class="line">			System.out.println(&quot;所有线程的解析结果：&quot;+result);</span><br><span class="line">		&#125; </span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args) throws InterruptedException &#123;</span><br><span class="line">		Thread[] threads=new Thread[threadCount];</span><br><span class="line">		for(int i=0;i&lt;threadCount;i++)&#123;</span><br><span class="line">			threads[i]=new Thread(new Parser(&quot;Parser-&quot;+i));</span><br><span class="line">		&#125; </span><br><span class="line">		for(int i=0;i&lt;threadCount;i++)&#123;</span><br><span class="line">			threads[i].start();</span><br><span class="line">		&#125;   </span><br><span class="line">	&#125; </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">输出：</span><br><span class="line">1471866228774-Parser-4线程的解析结果：631026992</span><br><span class="line">1471866228930-Parser-3线程的解析结果：-372785277</span><br><span class="line">1471866228961-Parser-1线程的解析结果：-938473891</span><br><span class="line">1471866229008-Parser-7线程的解析结果：-396620018</span><br><span class="line">1471866229008-Parser-2线程的解析结果：-1159985406</span><br><span class="line">1471866229024-Parser-5线程的解析结果：-664234808</span><br><span class="line">1471866229070-Parser-6线程的解析结果：556534377</span><br><span class="line">1471866229117-Parser-9线程的解析结果：-844558478</span><br><span class="line">1471866229383-Parser-0线程的解析结果：919864023</span><br><span class="line">1471866229430-Parser-8线程的解析结果：-2104111089</span><br><span class="line">所有线程解析结束！</span><br><span class="line">所有线程的解析结果：-78376279</span><br><span class="line">1471866229430-Parser-8线程越过屏障！</span><br><span class="line">1471866229430-Parser-2线程越过屏障！</span><br><span class="line">1471866229430-Parser-9线程越过屏障！</span><br><span class="line">1471866229430-Parser-7线程越过屏障！</span><br><span class="line">1471866229430-Parser-1线程越过屏障！</span><br><span class="line">1471866229430-Parser-3线程越过屏障！</span><br><span class="line">1471866229430-Parser-0线程越过屏障！</span><br><span class="line">1471866229430-Parser-6线程越过屏障！</span><br><span class="line">1471866229430-Parser-4线程越过屏障！</span><br><span class="line">1471866229430-Parser-5线程越过屏障！</span><br><span class="line">// 各个线程解析完成的时间不一致，但是越过屏障的时间却是一致的。</span><br></pre></td></tr></table></figure>





<h1 id="控制并发线程数的信号量Semaphore"><a href="#控制并发线程数的信号量Semaphore" class="headerlink" title="控制并发线程数的信号量Semaphore"></a>控制并发线程数的信号量Semaphore</h1><h2 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h2><p>Semaphore(信号量)用来控制同时访问特定资源的线程数量，它通过协调各个线程，以保证合理的使用公共资源。</p>
<p>Semaphore可以用于做<strong>流量控制</strong>，特别是公用资源有限的应用场景，比如数据库连接。</p>
<p>当需要批量处理大量的数据文件时，可以开启几十个线程并发读取文件。将文件读取到内存中之后，还需要将解析后的数据存储的数据库中，但是数据库有允许的最大连接数，比如是10个，就必须要控制只有10个线程可以获取到数据库连接。这个时候就可以用Semaphore来做流量的控制。</p>
<h2 id="使用-2"><a href="#使用-2" class="headerlink" title="使用"></a>使用</h2><p>在构造函数中，可以传入两个参数：</p>
<ul>
<li><code>permits</code>： 可用的许可证数量</li>
<li><code>fair</code>： 是否公平获取许可证</li>
</ul>
<p>比如<code>Semaphore(10，true)</code>，就表示允许10个线程获取许可证，也就是最大的并发量为10，线程可以通过公平竞争（即先进先出的顺序）的方式获取许可证。</p>
<p>线程使用Semaphore的<code>acquire()</code>方法获取一个许可证，使用完之后调用<code>release()</code>方法归还许可证。还可以用<code>tryAcquire()</code>方法尝试获取许可证。 </p>
<p><strong>其他的API</strong></p>
<ul>
<li><code>public final boolean hasQueuedThreads()</code>： 是否还有线程正在等待获取许可证</li>
<li><code>public final int getQueueLength() </code>：判断还有多少个等待获取许可证的线程</li>
<li><code>public int availablePermits() </code>：返回此信号量中当前可用的许可证数量</li>
<li><code>public void acquire()</code>： 从此信号量中请求一个许可证</li>
<li><code>public void release()</code>： 从此信号量中释放一个许可证</li>
<li><code>public boolean tryAcquire()</code>： 试图从信号量中请求一个许可证，无可用的许可证时，直接返回不阻塞；</li>
</ul>
<h2 id="测试类-2"><a href="#测试类-2" class="headerlink" title="测试类"></a>测试类</h2><p>代码中有30个线程在执行，但是只允许10个并发执行。Semaphore（10）表示允许10个线程获取许可证，也就是最大并发数是10。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">import java.util.concurrent.ExecutorService;</span><br><span class="line">import java.util.concurrent.Executors;</span><br><span class="line">import java.util.concurrent.Semaphore;</span><br><span class="line"> </span><br><span class="line">public class SemaphoreTest &#123; </span><br><span class="line">	private static final int THREAD_COUNT = 30;</span><br><span class="line">	private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);</span><br><span class="line">	private static Semaphore s = new Semaphore(10);</span><br><span class="line">	</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		for (int i = 0; i &lt; THREAD_COUNT; i++) &#123;</span><br><span class="line">			threadPool.execute(new Runnable() &#123;</span><br><span class="line">				@Override</span><br><span class="line">				public void run() &#123;</span><br><span class="line">					try &#123; </span><br><span class="line">						s.acquire();</span><br><span class="line">						System.out.println(&quot;save data&quot;);</span><br><span class="line">						s.release();</span><br><span class="line">					&#125; catch (InterruptedException e) &#123;</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;);</span><br><span class="line">		&#125;</span><br><span class="line">		threadPool.shutdown();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h1 id="线程间交换数据的交换者Exchanger"><a href="#线程间交换数据的交换者Exchanger" class="headerlink" title="线程间交换数据的交换者Exchanger"></a>线程间交换数据的交换者Exchanger</h1><h2 id="使用-3"><a href="#使用-3" class="headerlink" title="使用"></a>使用</h2><p>Exchanger（交换者）是一个用于线程间协作的工具类。Exchanger用于进行线程间的数据交换。它提供一个同步点，供两个线程交换数据。</p>
<p>如果第一个线程先执行exchange()方法，它会一直等待第二个线程也执行exchange方法，当两个线程都到达同步点时，这两个线程就可以交换数据，将本线程生产出来的数据传递给对方。</p>
<p>如果两个线程有一个没有执行exchange()方法，则会一直等待，如果担心有特殊情况发生，避免一直等待，可以使用<code>exchange（V x，longtimeout，TimeUnit unit）</code>设置最大等待时长。</p>
<h2 id="应用场景-1"><a href="#应用场景-1" class="headerlink" title="应用场景"></a>应用场景</h2><p>下面来看一下Exchanger的应用场景。</p>
<p>1、Exchanger可以用于遗传算法，遗传算法里需要选出两个人作为交配对象，这时候会交换两人的数据，并使用交叉规则得出2个交配结果。</p>
<p>2、Exchanger也可以用于校对工作，比如我们需要将纸制银行流水通过人工的方式录入成电子银行流水，为了避免错误，采用AB岗两人进行录入，录入到Excel之后，系统需要加载这两个Excel，并对两个Excel数据进行校对，看看是否录入一致。</p>
<h2 id="测试类-3"><a href="#测试类-3" class="headerlink" title="测试类"></a>测试类</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">import java.util.concurrent.Exchanger;</span><br><span class="line">import java.util.concurrent.ExecutorService;</span><br><span class="line">import java.util.concurrent.Executors;</span><br><span class="line"> </span><br><span class="line">public class ExchangerTest &#123;</span><br><span class="line"> </span><br><span class="line">	private static final Exchanger&lt;String&gt; exgr = new Exchanger&lt;String&gt;();</span><br><span class="line">	private static ExecutorService threadPool = Executors.newFixedThreadPool(2);</span><br><span class="line"> </span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		threadPool.execute(new Runnable() &#123;</span><br><span class="line">			@Override</span><br><span class="line">			public void run() &#123;</span><br><span class="line">				try &#123;</span><br><span class="line">					String A = &quot;银行流水100&quot;;// A录入银行流水数据</span><br><span class="line">					String B=exgr.exchange(A);</span><br><span class="line">					System.out.println(&quot;A的视角：A和B数据是否一致：&quot; + A.equals(B) + </span><br><span class="line">&quot;，A录入的是：&quot; + A + &quot;，B录入是：&quot; + B);</span><br><span class="line">				&#125; catch (InterruptedException e) &#123;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">		threadPool.execute(new Runnable() &#123;</span><br><span class="line">			@Override</span><br><span class="line">			public void run() &#123;</span><br><span class="line">				try &#123;</span><br><span class="line">					String B = &quot;银行流水200&quot;;// B录入银行流水数据</span><br><span class="line">					String A = exgr.exchange(B);</span><br><span class="line">					System.out.println(&quot;B的视角：A和B数据是否一致：&quot; + A.equals(B) + </span><br><span class="line">&quot;，A录入的是：&quot; + A + &quot;，B录入是：&quot; + B);</span><br><span class="line">				&#125; catch (InterruptedException e) &#123;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">		threadPool.shutdown();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">输出：</span><br><span class="line"></span><br><span class="line">B的视角：A和B数据是否一致：false，A录入的是：银行流水100，B录入是：银行流水200</span><br><span class="line">A的视角：A和B数据是否一致：false，A录入的是：银行流水100，B录入是：银行流水200</span><br></pre></td></tr></table></figure>



<h1 id="LockSupport"><a href="#LockSupport" class="headerlink" title="LockSupport"></a>LockSupport</h1><h2 id="使用-4"><a href="#使用-4" class="headerlink" title="使用"></a>使用</h2><p>LockSupport类，是JUC包中的一个工具类，是用来创建锁和其他同步类的基本线程阻塞原语，可以让线程在任意位置阻塞，也可以在任意位置唤醒。（<a target="_blank" rel="noopener" href="https://docs.oracle.com/javase/8/docs/api/">Basic thread blocking primitives for creating locks and other synchronization classes</a>）</p>
<p>核心方法有两个：<code>park()</code>和<code>unpark()</code>，其中<code>park()</code>方法用来阻塞当前调用线程，<code>unpark()</code>方法用于唤醒指定线程。</p>
<p><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/dc5602eafd51">ReentrantLock</a>,<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/4a624281235e">ReentReadWriteLocks</a>在线程间等待/通知机制使用的<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/28387056eeb4">Condition</a>时都会调用LockSupport.park()方法和LockSupport.unpark()方法。</p>
<h2 id="与wait-notify对比"><a href="#与wait-notify对比" class="headerlink" title="与wait/notify对比"></a>与wait/notify对比</h2><p>这和Object类的wait()和notify()方法有些类似，这里主要有两点区别：</p>
<p>（1）wait和notify都是Object中的方法，在调用这两个方法前必须先获得锁对象，但是park不需要获取某个对象的锁就可以锁住线程。</p>
<p>（2）notify只能随机选择一个线程唤醒，无法唤醒指定的线程，unpark却可以唤醒一个指定的线程。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">public class WaitNotifyTest &#123;</span><br><span class="line">    private static Object obj = new Object();</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        new Thread(new WaitThread()).start();</span><br><span class="line">        new Thread(new NotifyThread()).start();</span><br><span class="line">    &#125;</span><br><span class="line">    static class WaitThread implements Runnable &#123;</span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            synchronized (obj) &#123;</span><br><span class="line">                System.out.println(&quot;start wait!&quot;);</span><br><span class="line">                try &#123;</span><br><span class="line">                    obj.wait();</span><br><span class="line">                &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                System.out.println(&quot;end wait!&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    static class NotifyThread implements Runnable &#123;</span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            synchronized (obj) &#123;</span><br><span class="line">                System.out.println(&quot;start notify!&quot;);</span><br><span class="line">                obj.notify();</span><br><span class="line">                System.out.println(&quot;end notify!&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">输出：</span><br><span class="line">start wait!</span><br><span class="line">start notify!</span><br><span class="line">end notify!</span><br><span class="line">end wait!</span><br></pre></td></tr></table></figure>





<h2 id="测试类-4"><a href="#测试类-4" class="headerlink" title="测试类"></a>测试类</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">public class LockSupportTest &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        Thread parkThread = new Thread(new ParkThread());</span><br><span class="line">        parkThread.start();</span><br><span class="line">        System.out.println(&quot;开始线程唤醒&quot;);</span><br><span class="line">        LockSupport.unpark(parkThread);</span><br><span class="line">        System.out.println(&quot;结束线程唤醒&quot;);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    static class ParkThread implements Runnable&#123;</span><br><span class="line"></span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            System.out.println(&quot;开始线程阻塞&quot;);</span><br><span class="line">            LockSupport.park();</span><br><span class="line">            System.out.println(&quot;结束线程阻塞&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">输出：</span><br><span class="line">开始线程阻塞</span><br><span class="line">开始线程唤醒</span><br><span class="line">结束线程阻塞</span><br><span class="line">结束线程唤醒</span><br></pre></td></tr></table></figure>



<h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><p>经过测试我们发现，先唤醒线程，在阻塞线程，线程不会真的阻塞；但是先唤醒线程两次再阻塞两次时就会导致线程真的阻塞。</p>
<p>LockSupport使用了一种名为Permit（许可）的概念来做到阻塞和唤醒线程的功能，通过控制变量<code>_counter</code>进行控制的，类似于(0,1)信号量。</p>
<ul>
<li>当调用<code>park()</code>方法时，会将_counter置为0，同时判断前值，小于1说明前面被<code>unpark</code>过，则直接退出，否则将使该线程阻塞。</li>
<li>当调用<code>unpark()</code>方法时，会将_counter置为1，同时判断前值，小于1会进行线程唤醒，否则直接退出。</li>
<li>形象的理解，线程阻塞需要消耗凭证(permit)，这个凭证最多只有1个。当调用park方法时，如果有凭证，则会直接消耗掉这个凭证然后正常退出；但是如果没有凭证，就必须阻塞等待凭证可用；而unpark则相反，它会增加一个凭证，但凭证最多只能有1个。</li>
<li>为什么可以先唤醒线程后阻塞线程？<br>因为unpark获得了一个凭证,之后调用park因为有凭证消费，故不会阻塞。</li>
<li>为什么唤醒两次后阻塞两次会阻塞线程。<br>因为凭证的数量最多为1，连续调用两次unpark和调用一次unpark效果一样，只会增加一个凭证；而调用两次park却需要消费两个凭证。</li>
</ul>
<p>参考：</p>
<p>《Java并发编程的艺术》</p>
<p>Java并发工具类：<a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_36208314/article/details/115077591">https://blog.csdn.net/weixin_36208314/article/details/115077591</a></p>
<p>Java并发工具类详解：<a target="_blank" rel="noopener" href="https://blog.csdn.net/sunxianghuang/article/details/52277394">https://blog.csdn.net/sunxianghuang/article/details/52277394</a></p>
<p>LockSupport功能简介及原理浅析：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/takumicx/p/9328459.html">https://www.cnblogs.com/takumicx/p/9328459.html</a></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2021/06/08/Java/Java%E5%B9%B6%E5%8F%91%E5%B7%A5%E5%85%B7%E7%B1%BB(JUC)/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java/" rel="tag">Java</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2021/06/12/resource/finance/%E9%87%91%E9%92%B1%E5%85%89%E8%B0%B1/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            金钱光谱
          
        </div>
      </a>
    
    
      <a href="/2021/06/06/resource/finance/%E9%80%82%E5%90%88%E6%99%AE%E9%80%9A%E4%BA%BA%E7%9A%84%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">适合普通人的量化投资</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2021
        <i class="ri-heart-fill heart_icon"></i> Chenyy
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="ChenyyのBlog"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">文章</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/book">收藏</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about/me">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>